package com.ncr.travel.tas.configuration.model;

import java.util.Iterator;

import com.ncr.travel.tas.configuration.exceptions.TableCellException;
import com.ncr.travel.tas.configuration.exceptions.TableColumnException;
import com.ncr.travel.tas.configuration.exceptions.TableRowException;

public class TableValue extends ConfigurationValue {

	public TableValue(ConfigurationValue value) {

		super.setChildValues(value.getChildValues());
		super.setId(value.getId());
		super.setKeyName(value.getKeyName());
		super.setObjectType(value.getObjectType());
		super.setParent(value.getParent());
		super.setParentValue(value.getParentValue());
		super.setTemplate(value.getTemplate());
		super.setTableRows(value.getTableRows());
		super.setTableColumns(value.getTableColumns());
		super.setRow(value.getRow());
		super.setColumn(value.getColumn());

	}

	public TableValue() {
		// set our value to our class type to flag as table value
		this.setObjectType(this.getClass().getSimpleName());
	}

	private static final long serialVersionUID = 3L;

	public void setValue(int row, int column, Object d) throws TableRowException, TableColumnException {

		ConfigurationValue value = new ConfigurationValue();

		// check to make sure the request can be fulfilled
		int rows = this.getTableRows().size();
		int cols = this.getTableColumns().size();

		if (row >= rows) {
			throw new TableRowException("Row " + row + "has not been defined");
		}

		if (column >= cols) {
			throw new TableColumnException("Column " + row + "has not been defined");
		}

		value.setValue(d);
		value.setKeyName(row + ":" + column);
		value.setRow(row);
		value.setColumn(column);
		value.setParentValue(this);

		this.addChildValue(value);
	}

	public void setCell(int row, int column, Object d, ConfigurationValueTemplate template) {

		ConfigurationValue value = new ConfigurationValue();

		value.setValue(d);
		value.setKeyName(row + ":" + column);
		value.setParentValue(this);
		value.setTemplate(template);
		value.setLocation(row, column);
		this.addChildValue(value);

	}

	public ConfigurationValue getCell(int row, int col) throws TableCellException {

		Iterator<ConfigurationValue> iter = this.getChildValues().iterator();

		while (iter.hasNext()) {

			ConfigurationValue cv = iter.next();
			if (cv.getRow() == row && cv.getColumn() == col) {
				return cv;
			}
		}

		throw new TableCellException("Cell not found at " + row + ":" + col);

	}

}
